package com.jianbing.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.ui.ModelMap;

import com.jianbing.dao.MongoDBDao;
import com.jianbing.entity.AccessToken;
import com.jianbing.entity.Customer;
import com.jianbing.entity.CustomerProduct;
import com.jianbing.entity.Goods;
import com.jianbing.entity.Result;
import com.jianbing.entity.TaskStatus;
import com.jianbing.service.NoticeDataWarehouseService;
import com.jianbing.service.ThxdService;
import com.jianbing.timer.CitySetting;
import com.jianbing.util.Constants;
import com.jianbing.util.HttpClient;
import com.jianbing.util.IDCardUtil;
import com.jianbing.util.SignUtil;
import com.jianbing.util.StringFuzzyMatchUtils;
import com.jianbing.util.StringUtils;
import com.jianbing.util.TableUtil;
import com.mongodb.BasicDBObject;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

@Service
public class ThxdServiceImpl implements ThxdService {

	Logger logger = Logger.getLogger(ThxdServiceImpl.class);

	@Autowired
	private NoticeDataWarehouseService noticeDataWarehouseService;

	@SuppressWarnings("unchecked")
	@Override
	public Result getThxdSettings(Result result, String appKey, String token, String provName,
			String operatorTypeName) {
		Date now = new Date();
		ModelMap model = new ModelMap();
		Map<String, Object> thxdCityMap = CitySetting.thxdCityMap;
		if (thxdCityMap.size() <= 0) {
			result.setCode(-1);
			result.setMsg("暂无城市配置信息，请稍后再试");
			return result;
		}
		try {
			BasicDBObject queryObject = new BasicDBObject();
			queryObject.append("appKey", appKey);
			AccessToken accessToken = MongoDBDao.findOne(TableUtil.accessToken, AccessToken.class, queryObject);
			if (accessToken == null || accessToken.getActiveTime() < now.getTime()) {
				result.setCode(-1);
				result.setMsg("token已失效");
				return result;
			}

			BasicDBObject goodsQueryObject = new BasicDBObject();
			goodsQueryObject.append("goodsType", Constants.thxd);
			Goods goods = MongoDBDao.findOne(TableUtil.goods, Goods.class, goodsQueryObject);
			queryObject.append("goodsSn", goods.getGoodsSn());
			CustomerProduct customerProduct = MongoDBDao.findOne(TableUtil.customer_product, CustomerProduct.class,
					queryObject);
			String openCityList = customerProduct.getCityList();
			List<Map<String, Object>> thxdCityList = JSONArray.fromObject(thxdCityMap.get("thxdCity"));
			for (Map<String, Object> thxdCity : thxdCityList) {
				if (thxdCity.get("provinceName").toString().contains(provName)) {
					List<Map<String, Object>> cityList = JSONArray.fromObject(thxdCity.get("citys"));
					List<String> cityNameList = new ArrayList<>();
					for (Map<String, Object> city : cityList) {
						if ((Integer) city.get("state") == Constants.NORMAL) {
							if (StringUtils.isNotEmpty(operatorTypeName)
									&& city.get("operatorTypeName").equals(operatorTypeName)) {
								if (openCityList.equals(Constants.thxd_city_open_all)) {
									// 支持所有城市
									model.addAttribute("citySetting", city);
									result.setData(model);
									break;
								} else if ((openCityList.contains(Constants.thxd_operator_yidong)
										&& operatorTypeName.equals(Constants.thxd_operator_yidong))
										|| (openCityList.contains(Constants.thxd_operator_liantong)
												&& operatorTypeName.equals(Constants.thxd_operator_liantong))
										|| (openCityList.contains(Constants.thxd_operator_dianxin)
												&& operatorTypeName.equals(Constants.thxd_operator_dianxin))) {
									model.addAttribute("citySetting", city);
									result.setData(model);
									break;
								} else if (openCityList.contains(String.valueOf(city.get("id")))) {
									model.addAttribute("citySetting", city);
									result.setData(model);
									break;
								} else {
									result.setCode(-1);
									result.setMsg("对不起，您尚未开通此城市");
								}
								break;
							} else {
								if (StringUtils.isEmpty(operatorTypeName)) {
									if ((openCityList.equals(Constants.thxd_city_open_all)
											|| openCityList.contains(String.valueOf(city.get("id"))))) {
										cityNameList.add(city.get("name").toString() + city.get("operatorTypeName"));
									} else {
										if ((openCityList.contains(Constants.thxd_operator_yidong)
												&& city.get("operatorTypeName").equals(Constants.thxd_operator_yidong))
												|| (openCityList.contains(Constants.thxd_operator_liantong)
														&& city.get("operatorTypeName")
																.equals(Constants.thxd_operator_liantong))
												|| (openCityList.contains(Constants.thxd_operator_dianxin)
														&& city.get("operatorTypeName")
																.equals(Constants.thxd_operator_dianxin))) {
											cityNameList
													.add(city.get("name").toString() + city.get("operatorTypeName"));
										}
									}
								}
							}
						}
					}
					if (cityNameList.size() > 0) {
						model.addAttribute("cityNameList", cityNameList);
						result.setData(model);
					}
					break;
				}
			}
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			result.setCode(-1);
			result.setMsg("服务器错误");
			return result;
		}
		return result;
	}

	@SuppressWarnings("static-access")
	@Override
	public Result queryThxdData(Result result, JSONObject json) throws Exception {
		ModelMap model = new ModelMap();
		Date now = new Date();
		JSONObject jsonParam = JSONObject.fromObject(json.get("params"));
		MongoDBDao dbDao = new MongoDBDao();
		BasicDBObject queryObject = new BasicDBObject();
		queryObject.append("appKey", jsonParam.get("appKey"));
		Customer customer = dbDao.findOne(TableUtil.customer, Customer.class, queryObject);
		if (customer == null) {
			result.setCode(102);
			result.setMsg("无效的appKey");
			return result;
		}
		AccessToken accessToken = MongoDBDao.findOne(TableUtil.accessToken, AccessToken.class, queryObject);
		if (accessToken == null || accessToken.getActiveTime() < now.getTime()) {
			result.setCode(103);
			result.setMsg("token已超时");
			return result;
		}
		if ((jsonParam.getLong("timestamp") + Constants.accessTime * 1000) < now.getTime()
				|| !SignUtil.checkSign(json.getString("sign"), jsonParam, customer.getAppSecret())) {
			result.setCode(104);
			result.setMsg("签名错误");
			return result;
		}
		// 从数据仓库获取数据并校验
		String thxdDataResult = HttpClient.get(Constants.thxd_data_url + jsonParam.getString("orderSn"));
		if (StringUtils.isEmpty(thxdDataResult) || JSONObject.fromObject(thxdDataResult).getInt("code") != 0) {
			result.setCode(105);
			result.setMsg("无此订单数据");
			return result;
		}
		JSONObject thxdDataJson = JSONObject.fromObject(thxdDataResult);
		JSONObject raw_data = JSONObject.fromObject(thxdDataJson.get("raw_data"));
//		JSONObject mobile_brief = JSONObject.fromObject(raw_data.get("mobile_brief"));
//		String name = mobile_brief.get("name").toString().replaceAll("x", "*");
//		String ID = mobile_brief.get("ID").toString();
//		String phone = mobile_brief.get("number").toString();
//		if (StringUtils.isNotEmpty(name)
//				&& !StringFuzzyMatchUtils.checkStringMatching2(jsonParam.getString("name"), name)) {
//			result.setCode(106);
//			result.setMsg("姓名匹配失败");
//			return result;
//		}
//		if (StringUtils.isNotEmpty(ID) && (!IDCardUtil.IDCardValidate(jsonParam.getString("ID"))
//				|| !StringFuzzyMatchUtils.checkStringMatching2(jsonParam.getString("ID"), ID))) {
//			result.setCode(107);
//			result.setMsg("身份证号匹配失败");
//			return result;
//		}
//		if (StringUtils.isEmpty(phone)
//				|| !StringFuzzyMatchUtils.checkStringMatching2(jsonParam.getString("phone"), phone)) {
//			result.setCode(108);
//			result.setMsg("手机号码匹配失败");
//			return result;
//		}
		logger.info("通话详单数据查询成功" + raw_data);
		// 返回数据给合作方
		model.addAttribute("thxdData", thxdDataJson);
		result.setData(model);
		// 向数据仓库上传用户信息
		Map<String, Object> noticeMsg = new HashMap<String, Object>();
		Map<String, String> params = new HashMap<String, String>();
		params.put("orderid", jsonParam.getString("orderSn"));
		params.put("name", jsonParam.getString("name"));
		params.put("id", jsonParam.getString("ID"));
		params.put("phone", jsonParam.getString("phone"));
		params.put("serviceType", "phone");
		noticeMsg.put("params", params);
		noticeMsg.put("url", Constants.data_notice_url);
		noticeDataWarehouseService.producer(JSONObject.fromObject(noticeMsg).toString());
		logger.info("通知数据仓库通话详单用户信息  success" + noticeMsg);
		return result;
	}

	@Override
	public List<TaskStatus> queryThxdTaskStatus(String orderSn, Integer taskId, String status) {
		BasicDBObject queryObject = new BasicDBObject();
		if (StringUtils.isNotEmpty(orderSn)) {
			queryObject.append("orderSn", orderSn);
		}
		if (StringUtils.isNotEmpty(status)) {
			queryObject.append("status", status);
		}
		if (taskId != null) {
			queryObject.append("taskId", taskId);
		}
		List<TaskStatus> thxdTaskStatusList = MongoDBDao.queryForList(TableUtil.thxdTaskStatusTable, TaskStatus.class,
				queryObject, null, null, null, null);
		return thxdTaskStatusList;
	}

	@Override
	public void updateThxdTaskStatus(TaskStatus taskStatus) throws Exception {
		Date now = new Date();
		BasicDBObject queryObject = new BasicDBObject();
		queryObject.append("orderSn", taskStatus.getOrderSn());
		TaskStatus thxdTaskStatus = MongoDBDao.findOne(TableUtil.thxdTaskStatusTable, TaskStatus.class, queryObject);
		if (thxdTaskStatus == null) {
			thxdTaskStatus = new TaskStatus();
			thxdTaskStatus.setOrderSn(taskStatus.getOrderSn());
			thxdTaskStatus.setTaskId(taskStatus.getTaskId());
			thxdTaskStatus.setStatus(taskStatus.getStatus());
			thxdTaskStatus.setCreateTime(now);
			thxdTaskStatus.setUpdateTime(now);
			thxdTaskStatus.setPhone(taskStatus.getPhone());
			MongoDBDao.insert(TableUtil.thxdTaskStatusTable, thxdTaskStatus);
		} else {
			thxdTaskStatus.setStatus(taskStatus.getStatus());
			thxdTaskStatus.setUpdateTime(now);
			thxdTaskStatus.setTaskId(taskStatus.getTaskId());
			if (taskStatus.getCreateTime() != null) {
				thxdTaskStatus.setCreateTime(taskStatus.getCreateTime());
			}

			MongoDBDao.update(TableUtil.thxdTaskStatusTable, queryObject, thxdTaskStatus);
		}
	}

}
